<template>
  <div class="grid-setting"
       id="grid-setting">
    <el-radio-group v-model="activeSetting"
                    size="mini">
      <el-radio-button label="gridSetting">Grid Option</el-radio-button>
      <el-radio-button label="columnsSetting">Columns Setting</el-radio-button>
      <!--<el-radio-button label="event">Event</el-radio-button>-->
    </el-radio-group>
    <el-form ref="gridSetting"
             :model="setting"
             label-position="top"
             v-show="activeSetting==='gridSetting'"
             style="height:auto;">
      <el-form-item label="GridLines"  v-if="!comIsTable">
        <el-select v-model="setting.report.gridLines"
                   placeholder="Please select">
          <el-option v-for="(item,index) in gridLinesOptions"
                     :key="index"
                     :label="item"
                     :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Toolbar">
        <el-checkbox-group v-model="setting.report.toolbar">
          <el-checkbox label="PdfExport"></el-checkbox>
          <!-- <el-checkbox label="ExcelExport"></el-checkbox> -->
          <el-checkbox label="CsvExport"></el-checkbox>
          <el-checkbox label="ColumnChooser"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!--<el-form-item label="showColumnChooser">
        <el-switch v-model="setting.report.showColumnChooser"></el-switch>
      </el-form-item>-->
      <el-form-item label="Show Paging" v-if="setting.report.gridStyle !== 'List'">
        <el-switch v-model="setting.report.allowPaging"></el-switch>
      </el-form-item>
      <el-form-item label="Show Toolbar">
        <el-switch v-model="setting.report.allowGrouping"
                   @change="allowGrouping"></el-switch>
      </el-form-item>
      <el-form-item label="Auto Fit" v-if="setting.report.gridStyle !== 'List'">
        <el-switch v-model="setting.report.autoFit"></el-switch>
      </el-form-item>
      <el-form-item label="Auto Scroll" v-if="setting.report.gridStyle !== 'List'">
        <el-switch v-model="setting.report.autoScroll"></el-switch>
      </el-form-item>
      <el-form-item label="Show Export Option">
        <el-switch v-model="setting.report.showExportOption"></el-switch>
      </el-form-item>
      <el-form-item label="Font Size (px)"  v-if="setting.report.gridStyle !== 'List'">
        <el-input style="max-width:217px"
                  v-model="setting.report.fontsize">px</el-input>
      </el-form-item>
      <!-- <el-form-item label="Row Height (px)">
        <el-input style="max-width:217px"
                  v-model="setting.report.rowHeight">px</el-input>
      </el-form-item> -->
      <el-form-item label="Grid Style">
        <el-select v-model="setting.report.gridStyle"
                   placeholder="Please select">
          <el-option v-for="item in gridStyleOptions"
                     :key="item"
                     :label="item"
                     :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Scroll Speed" style="display:none">
        <el-select v-model="setting.report.scrollSpeed"
                   placeholder="Please select">
          <el-option v-for="item in scrollSpeedOptions"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-show="activeSetting==='columnsSetting'">
      <el-switch v-model="expandAllColumn"
                 active-text="Expand All"
                 inactive-text=""
                 @change="expandAll"></el-switch>
      <draggable handle=".mover"
                 filter=".edititem"
                 v-model="setting.report.columns"
                 chosenClass="chosen"
                 forceFallback="true"
                 animation="1000">
        <transition-group>
          <div class="item_drag"
               v-for="(item,index) in setting.report.columns"
               :key="item.field">
            <el-card class="column-card">
              <el-row type="flex"
                      class="row-bg mover">
                <el-col :span="16">
                  <div>
                    <span class="column-field">{{item.field}} </span><i class="column-type">: {{item.type}}</i>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div style="float:right">
                    <el-tooltip :open-delay="1000"
                                class="item"
                                effect="dark"
                                :content="item.visible ? 'Display Column ' : 'Hide Column'"
                                placement="bottom-end">
                      <el-link style="float: left; border: none;"
                               :underline="false"
                               @click.native="toggleVisible(index, item.visible)"><i v-bind:class="[item.visible ? 'cuifont icon_eye_show': 'cuifont icon_eye_hide','edititem']"
                           style="margin-left: 5px;"></i></el-link>
                    </el-tooltip>
                    <el-link style="margin-left:5px"
                             class="column-link edititem"
                             :underline="false"
                             @click.native="showSettingClick(index, item.showSetting)"><i v-bind:class="[item.showSetting ? 'el-icon-arrow-up': 'el-icon-arrow-down']"
                         style="margin-left: 5px;"></i></el-link>
                    <!-- <el-link class="column-link" :underline="false" @click.native="upSortClick(index)" v-show="index != 0"><i class="el-icon-top"></i></el-link>
                    <el-link class="column-link" :underline="false" @click.native="downSortClick(index)" v-show="index != setting.report.columns.length-1"><i class="el-icon-bottom"></i></el-link> -->
                  </div>
                </el-col>
              </el-row>
              <el-form label-position="left"
                       v-show="item.showSetting"
                       label-width="120px"
                       style="border-top: 1px solid #EBEEF5;padding-top: 10px;">
                <input hidden
                       name="field"
                       v-model="item.field" />
                <el-form-item label="Header Text">
                  <el-input v-model="item.headerText"></el-input>
                </el-form-item>
                <el-form-item label="Header tooltip"
                              style="margin-bottom: 5px;margin-top: 5px;">
                  <el-input v-model="item.headerTextTooltip"></el-input>
                </el-form-item>
                <el-form-item label="Text Align">
                  <el-select v-model="item.textAlign"
                             placeholder="Please select">
                    <el-option label="Left"
                               value="Left"></el-option>
                    <el-option label="Center"
                               value="Center"></el-option>
                    <el-option label="Right"
                               value="Right"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="Allow Filtering" v-if="!comIsTable">
                  <el-switch v-model="item.allowFiltering"></el-switch>
                </el-form-item>
                <el-form-item label="Disable Html" v-if="!comIsTable">
                  <el-switch v-model="item.disableHtmlEncode"></el-switch>
                </el-form-item>
                <template v-if="setting.report.gridStyle !== 'List'">
                  <el-tooltip :open-delay="1000"
                            content="Fill in a number to set the column width you need."
                            placement="top-end" >
                    <el-form-item label="Max Width" v-if="!comIsTable">
                      <el-input v-model="item.maxWidth"
                                placeholder="Please Enter Max Width"></el-input>
                    </el-form-item>
                    <el-form-item label="Width" v-else>
                      <el-input v-model="item.maxWidth"
                                placeholder="Please Enter Width"></el-input>
                    </el-form-item>
                  </el-tooltip>
                </template>
             
                <!-- <el-form-item label="template">
                      <el-select v-model="item.template" placeholder="Please select" clearable>
                      <el-option v-for="(temItem,temIndex) in columnTemplates" :key="temIndex"  :label="temItem" :value="temItem"></el-option>
                    </el-select>
                    </el-form-item> -->
                <el-form-item label="Aggregates"
                              v-if="item.type === 'number'"
                              style="margin-bottom: 5px;margin-top: 5px;">
                  <el-checkbox-group v-model="item.aggregates"
                                     @change="checkboxChange($event,item)">
                    <el-select multiple
                               style="margin-right: 10px"
                               v-model="item.aggregates"
                               placeholder="Please select"
                               @change="selectChange($event,item)">
                      <el-option :label="list.label"
                                 :value="list.value"
                                 v-for="list in aggregates"
                                 :key="list.label">
                        <el-checkbox @click.native="(e) => {e.preventDefault()}"
                                     :label="list.label"></el-checkbox>
                      </el-option>
                    </el-select>
                    <aggregates-alias
                        :aggregatesArr="item.aggregatesArr"
                        :value="item.aggregates"
                        @submit="confirmAggregates($event, item)"/>
                  </el-checkbox-group>
                </el-form-item>
                <!-- <el-form-item label="Number Format"
                              v-if="item.type==='number'&&AveragePoint(item.aggregates)"
                              style="margin-bottom: 5px;margin-top: 5px;">
                  <el-select v-model="item.decimalPoint"
                             placeholder="Please select">
                    <el-option label="0"
                               :value="0"></el-option>
                    <el-option label="0.0"
                               :value="1"></el-option>
                    <el-option label="0.00"
                               :value="2"></el-option>
                    <el-option label="0.000"
                               :value="3"></el-option>
                    <el-option label="0.0000"
                               :value="4"></el-option>
                  </el-select>
                </el-form-item> -->
              </el-form>
            </el-card>
          </div>
        </transition-group>
      </draggable>
    </div>

  </div>
</template>

<script>
import draggable from 'vuedraggable'
import Index from '../../dashboard-filter/index.vue'
import { uniqBy } from 'lodash'
import aggregatesAlias from "@/components/gadget/grid-gadget/template/aggregatesAlias.vue";
export default {
  name: 'GridSetting',
  components: { Index, draggable, aggregatesAlias },
  data () {
    return {
      dataSource: [],
      dataSourceColumns: [],
      activeSetting: 'gridSetting',
      gridLinesOptions: ['Default', 'Both', 'None', 'Horizontal', 'Vertical'],
      gridStyleOptions: ['Data Grid', 'Table', "List"],
      scrollSpeedOptions: [
        { label: 'Slow', value: 8 },
        { label: 'Fast', value: 1 }
      ],
      columnTemplates: ['linkFormat', 'boolFormat', 'progessFormat', 'dateFormat', 'progessFullFormat', 'ticketLinkFormat', 'timeEntryLinkFormat', 'textFormat'],
      expandAllColumn: false,
      setting: {
        headerTitle: '',
        headerDescription: '',
        drillThroughStatus: true,
        report: {
          fontsize: 14,
          // rowHeight: 35,
          gridLines: 'Default',
          gridStyle:'Data Grid',
          scrollSpeed:8,
          showColumnMenu: true,
          allowResizing: true,
          allowFiltering: true,
          filterSettings: { type: 'Excel' },
          allowGrouping: false,
          allowPaging: true,
          autoFit:true,
          autoRatio:false,
          autoScroll:false,
          showExportOption: false,
          allowExcelExport: true,
          allowPdfExport: true,
          toolbar: ['PdfExport', 'CsvExport', 'ColumnChooser', 'ExcelExport'], // 'ExcelExport',
          showColumnChooser: true,
          groupOptions: { columns: ['name'] },
          allowReordering: true,
          allowSorting: true,
          allowTextWrap: true,
          pageSettings: { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000], pageCount: 4 },
          groupSettings: {
            allowReordering: false,
            columns: [],
            disablePageWiseAggregates: false,
            enableLazyLoading: false,
            showDropArea: true,
            showGroupedColumn: false,
            showToggleButton: false
          },
          columns: [

          ]
        }

      },
      aggregates: [
        {
          label: 'Sum',
          value: 'Sum'
        },
        {
          label: 'Average',
          value: 'Average'
        },
        {
          label: 'Min',
          value: 'Min'
        },
        {
          label: 'Max',
          value: 'Max'
        },
        {
          label: 'Count',
          value: 'Count'
        }
      ]
    }
  },
  props: {
    data:{
      type:Object,
      default:()=>({})
    }
  },
    created () {
    if (this.data) {
      this.$set(this.data)
    }
  },
  computed:{
    comIsTable(){
      return this.setting.report.gridStyle==='Table'
    }
  },
  watch: {
    data:{
       handler (newVal) {
        this.updateSetting(newVal)
      },
    },
   
    'setting.report.columns': {
      handler (newVal) {
        this.expandAllColumn = newVal.every(item => item.showSetting)
      },
      deep: true,
      immediate:true
    }
  },

  methods: {
    confirmAggregates (val, item) {
      item.aggregatesArr = val
    },
    AveragePoint (aggregates) {
      if (aggregates.includes('Average')) return true
      else return false
    },
    checkboxChange (e, item) {
      item.aggregates = e
      this.$forceUpdate()
    },
    selectChange (e, item) {
      item.aggregates = e
      this.$forceUpdate()
    },
    getData () {
      return this.setting
    },
    setColumns (dataSourceColumns) {
      dataSourceColumns.forEach(element => {
        if (element.type === 'number' && !element.hasOwnProperty('aggregates')) {
          element.aggregates = []
        }
        if (element.type === 'number' && !element.hasOwnProperty('decimalPoint')) {
          this.$set(element, 'decimalPoint', 2)
        }
      })
      this.$set(this.setting.report,'columns',dataSourceColumns)
      this.$forceUpdate()
    },
    allowGrouping (e) {
      this.$set(this.setting.report, 'allowGrouping', e)
      if (!e) {
        this.$set(this.setting.report, 'toolbar', [])
      }
      this.$forceUpdate()
    },
  
    toggleVisible (index, visible) {
      this.$set(this.setting.report.columns[index], 'visible', !visible)
      this.$forceUpdate()
    },
    showSettingClick (index, showSetting) {
      this.$set(this.setting.report.columns[index], 'showSetting', !showSetting)
      this.$forceUpdate()
    },
    expandAll (val) {
      this.setting.report.columns.filter(item => item.visible).forEach(item => {
        item.showSetting = val
      })
    },
    updateSetting (value, list, layerStatus) {
      let dataSourceColumns = []
      this._.merge(this.setting, value.gadgetSetting)
      if(value&&value.gadgetSetting&&value.gadgetSetting.report&&value.gadgetSetting.report.toolbar){
        this.setting.report.toolbar = value.gadgetSetting.report.toolbar
      }
      if (value && value.gadgetSetting && value.gadgetSetting.report &&
        value.gadgetSetting.report.columns && value.gadgetSetting.report.columns.length > 0 && !layerStatus) {
        dataSourceColumns = value.gadgetSetting.report.columns
      } else if (value && list) {
        value.gadgetSetting.report.columns.forEach(iii => {
          let item = list.find(i => i.name === iii.field)
          if (item) {
            dataSourceColumns.push({
              ...iii,
              type: this.convertType(item.dbType)})
          }
        })
        list.forEach(item => {
          const itemObj = {
            field: item.name,
            headerText: item.name,
            textAlign: item.dbType === 'number' ? 'Right' : 'Left',
            allowEditing: true,
            allowFiltering: true,
            allowGrouping: false,
            showExportOption: false,
            allowReordering: true,
            allowSearching: true,
            allowSorting: true,
            autoFit: true,
            autoRatio:false,
            autoScroll: false,
            disableHtmlEncode: false,
            enableGroupByFormat: false,
            foreignKeyField: item.name,
            showColumnMenu: true,
            showInColumnChooser: true,
            sortDirection: 'Descending',
            type: this.convertType(item.dbType),
            template: null,
            visible: true,
            showSetting: false,
            headerTextTooltip: null,
            maxWidth: 'auto'
          }
          if (value.gadgetSetting && value.gadgetSetting.report && value.gadgetSetting.report.columns) {
            const obj = this._.find(value.gadgetSetting.report.columns, { field: item.name })
            if (!obj) {
              dataSourceColumns.push(itemObj)
            }
          } else {
            dataSourceColumns.push(itemObj)
          }
        })
        dataSourceColumns = uniqBy(dataSourceColumns, 'foreignKeyField')
      }     
 
      this.setColumns(dataSourceColumns)
      this.$emit('update:data', this.setting)
      this.$forceUpdate()
      return dataSourceColumns
    },
    convertType (type) {
      return type
    },
    upSortClick (index) {
      let temp = this.setting.report.columns[index - 1]
      this.$set(this.setting.report.columns, index - 1, this.setting.report.columns[index])
      this.$set(this.setting.report.columns, index, temp)
      this.$forceUpdate()
    },
    downSortClick (index) {
      let temp = this.setting.report.columns[index + 1]
      this.$set(this.setting.report.columns, index + 1, this.setting.report.columns[index])
      this.$set(this.setting.report.columns, index, temp)
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss">
.grid-setting {
  .column-card {
    margin-top: 8px;
  }
  .el-card__body {
    padding: 5px 20px !important;
  }
  .column-field {
    font-weight: bold;
  }
  .column-type {
    color: #9ea1a7;
  }
  .column-link {
    float: left;
    border: none;
    margin-left: 3px;
  }
  .el-form-item .el-form-item {
    margin-bottom: 4px;
  }
}
</style>
<style scoped lang="scss">
.chosen {
  // border: solid 2px #3089dc !important;
}
.mover {
  // padding: 6px;
  // background-color: #fdfdfd;
  // border: solid 1px #eee;
  // margin-bottom: 10px;
  cursor: move;
  // width: 343px;
}
#grid-setting ::v-deep .el-switch__label.is-active {
  background-color: #fff !important;
}
</style>
